package org.example.demo;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class demo4_Insert {
    public static void main(String[] args) {
        //定义mysql数据源对象
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //设置数据库的连接串
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/mysql123?characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useSSL=false");
        //设置用户名
        mysqlDataSource.setUser("root");
        //设置密码
        mysqlDataSource.setPassword("123456");
        //定义JDBC的数据源对象
        DataSource dataSource = mysqlDataSource;

        //声明数据库连接对象
        Connection connection = null;
        //声明SQL语句的预处理对象
        PreparedStatement statement = null;
        //结果集
        ResultSet resultSet = null;

        try {
            //1.获取数据库连接
            connection = dataSource.getConnection();
            //2. 定义sql语句
            String sql = "insert into users (name) values(?)";
            //3.定义sql预处理对象
            statement = connection.prepareStatement(sql);
            //4.接收用户的输入
            Scanner scanner = new Scanner(System.in);
            String inputName = scanner.next();
            //5.用真实的数据替换占位符
            statement.setString(1,inputName);
            //6.执行sql
            int row = statement.executeUpdate();
            if (row == 1){
                System.out.println("插入成功");
            }else {
                System.out.println("插入失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
